import menuSlice from '@/reducers/menuSlice';
import { AppDispatch } from "@/store";
import { saveAs } from 'file-saver'
import { renderer } from '@/core/renderer';
import CommandBase from '@/core/command/base';
import { useAppDispatch, useAppSelector } from '@/store';
import { Form, Input, message, Modal, Radio } from 'antd';
import { parseFileName } from '@/utils/image';

export default class CommandFileSave implements CommandBase{
  static Component: React.FC = () => {
    const dispatch = useAppDispatch()
    const fileSave = useAppSelector((state) => state.menus.fileSave)

    return <>
      <Modal 
        title='另存为'
        width={540}
        open={fileSave.active} 
        closable={false}
        maskClosable={false}
        onOk={() => {
          renderer.mainCtx?.canvas.toBlob((blob) => {
            if(blob) {
              saveAs(blob, `${fileSave.form.name}.${fileSave.form.suffix}`)
              dispatch(menuSlice.actions.setFileSave({
                active: false
              }))
            }
            else message.error('数据异常，保存失败')
          })
        }} 
        onCancel={() => dispatch(menuSlice.actions.setFileSave({
          active: false
        }))}
      >
        <Form
          style={{
            paddingTop: 10
          }}
          component={'div'}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 14 }}
          initialValues={fileSave.form}
          onValuesChange={(changedValues) => dispatch(menuSlice.actions.setFileSave({
            form: changedValues
          }))}
        >
          <Form.Item label="文件名称" name="name">
            <Input placeholder="请输入" />
          </Form.Item>
          <Form.Item label="格式" name="suffix">
            <Radio.Group>
              <Radio value='png'>PNG</Radio>
              <Radio value='jpg'>JPG</Radio>
              <Radio value='jpeg'>JPEG</Radio>
              <Radio value='webp'>WEBP</Radio>
            </Radio.Group>
          </Form.Item>
        </Form>
      </Modal>
    </>
  }

  constructor(){
  }

  static triggerCommand(dispatch: AppDispatch){
    const firstImageLayer = renderer.layers.find(layer => {
      return layer.layerType == 'image'
    })
    const fileNameDetail = parseFileName(firstImageLayer?.name);
    dispatch(menuSlice.actions.setFileSave({
      active: true,
      form: {
        name: firstImageLayer ? fileNameDetail.name : Date.now(),
        suffix: fileNameDetail.suffix
      }
    }))
  }
}